<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb>
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片 -->
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="addRoleInfo">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 表格 -->
      <el-table :data="rolesList" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              :class="['bd_bottom', i1 === 0 ? 'bd_top' : '', 'vcenter']"
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
            >
              <!-- 一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="closeTag(scope.row, item1.id)">{{
                  item1.authName
                }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级三级权限 -->
              <el-col :span="19">
                <!-- 二级权限 -->
                <el-row
                  :class="[i2 !== 0 ? 'bd_top' : '', 'vcenter']"
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="closeTag(scope.row, item2.id)"
                      >{{ item2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级权限 -->
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      closable
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      @close="closeTag(scope.row, item3.id)"
                      >{{ item3.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>

        <!-- 序号 -->
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"> </el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"> </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              @click="editRoleInfo(scope.row)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              icon="el-icon-delete"
              @click="deleteRoleInfo(scope.row.id)"
              >删除</el-button
            >
            <el-button
              type="warning"
              icon="el-icon-setting"
              @click="showSetRightDialog(scope.row)"
              >分配权限
            </el-button>
            <!-- <pre>
              {{ scope.row }}
            </pre> -->
          </template>
        </el-table-column>
      </el-table>

      <!-- '添加角色的对话框 -->
      <el-dialog
        title="新建角色"
        :visible.sync="addDialogVisible"
        width="50%"
        @close="closeAddRole"
      >
        <!-- 表单 -->
        <el-form
          :model="addRole"
          :rules="addRoleRules"
          ref="addRuleForm"
          label-width="100px"
        >
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="addRole.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="addRole.roleDesc"></el-input>
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addRoleData">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 编辑角色的对话框 -->
      <el-dialog
        title="编辑角色"
        :visible.sync="editDialogVisible"
        width="50%"
        @close="closeEditRole"
      >
        <!-- 表单 -->
        <el-form
          :model="editRole"
          :rules="editRoleRules"
          ref="editRuleForm"
          label-width="100px"
        >
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="editRole.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="editRole.roleDesc"></el-input>
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editRoleData">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 删除角色的对话框 -->
      <el-dialog
        title="删除角色"
        :visible.sync="deleteDialogVisible"
        width="50%"
      >
        <span>确定要删除吗？</span>

        <span slot="footer" class="dialog-footer">
          <el-button @click="deleteDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="deleteRoleData">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 分配权限的对话框 -->
      <el-dialog
        title="分配权限"
        :visible.sync="setRightDialogVisible"
        width="50%"
        @close="closeSetRight"
      >
        <!-- 树状图 -->
        <el-tree
          ref="rightsListRef"
          :data="rightsList"
          :props="rightsProps"
          show-checkbox
          node-key="id"
          :default-checked-keys="checkedKeys"
          :default-expanded-keys="checkedKeys"
        ></el-tree>

        <span slot="footer" class="dialog-footer">
          <el-button @click="setRightDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="allotRights()">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'Roles',
  data() {
    return {
      // 角色列表
      rolesList: [],

      // 添加的角色信息
      addRole: {
        roleName: '',
        roleDesc: '',
      },
      // 是否开启添加角色的对话框
      addDialogVisible: false,
      // 添加角色规则
      addRoleRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
        ],
        roleDesc: [{ message: '请输入角色描述', trigger: 'blur' }],
      },

      // 编辑的角色信息
      editRole: {
        id: '',
        roleName: '',
        roleDesc: '',
      },
      // 是否开启编辑对话框
      editDialogVisible: false,
      // 编辑的规则
      editRoleRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
        ],
        roleDesc: [{ message: '请输入角色描述', trigger: 'blur' }],
      },

      // 删除角色信息
      deleteRole: {
        id: '',
      },
      // 是否开启删除对话框
      deleteDialogVisible: false,
      // 是否开启分配权限对话框
      setRightDialogVisible: false,
      // 权限列表
      rightsList: [],
      // 权限选项
      rightsProps: {
        children: 'children',
        label: 'authName',
      },
      // 默认选择的权限列表
      checkedKeys: [],
      // 权限 ID 列表
      rids: [],
      // 当前分配权限的id
      roleId: '',
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    // 获取角色列表
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error('获取失败')
      // 获取成功
      this.rolesList = res.data
    },

    // 添加角色信息
    addRoleInfo() {
      this.addDialogVisible = true
    },
    // 清除关闭对话框后的数据
    closeAddRole() {
      this.$refs.addRuleForm.resetFields()
    },
    // 添加角色到数据库
    addRoleData() {
      this.$refs.addRuleForm.validate(async (valid) => {
        if (!valid) return

        // 格式正确后  添加角色数据
        const { data: res } = await this.$http.post('roles', this.addRole)
        if (res.meta.status !== 201) return this.$message.error('创建失败')

        // 创建成功
        this.addDialogVisible = false
        this.$message.success('创建成功')
        this.getRolesList()
      })
    },

    // 编辑角色信息
    editRoleInfo(role) {
      this.editDialogVisible = true
      this.editRole = role
    },
    // 清空取消的编辑信息
    closeEditRole() {
      this.editRole = {}
      this.$refs.editRuleForm.resetFields()
    },
    // 保存修改的数据
    editRoleData() {
      this.$refs.editRuleForm.validate(async (valid) => {
        if (!valid) return

        // 保存修改后的数据
        const { data: res } = await this.$http.put(
          'roles/' + this.editRole.id,
          {
            roleName: this.editRole.roleName,
            roleDesc: this.editRole.roleDesc,
          }
        )
        if (res.meta.status !== 200) this.$message.error('获取失败')

        // 成功
        this.editDialogVisible = false
        this.$message.success = '获取成功'
        this.getRolesList()
      })
    },

    // 删除角色的信息
    deleteRoleInfo(id) {
      this.deleteDialogVisible = true
      this.deleteRole.id = id
    },
    // 删除角色数据
    async deleteRoleData() {
      const { data: res } = await this.$http.delete(
        'roles/' + this.deleteRole.id
      )
      if (res.meta.status !== 200) this.$message.error('Not Found')

      // 删除成功
      this.deleteDialogVisible = false
      this.$message.success('删除成功!')
      this.getRolesList()
    },
    // 删除标签
    async closeTag(role, rightId) {
      // 点击删除图标  弹出确认删除窗口
      const confirm = await this.$confirm(
        '此操作将永久删除该权限, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)

      if (confirm !== 'confirm') return this.$message.info('取消了删除操作')
      // 进行删除
      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${rightId}`
      )
      if (res.meta.status !== 200) this.$message.error('删除失败')
      // 删除成功
      this.$message.success('删除成功！')
      // 返回值是当前角色下最新的数据
      role.children = res.data
    },

    // 点击显示分配权限的对话框
    async showSetRightDialog(role) {
      this.roleId = role.id
      this.setRightDialogVisible = true
      // 获取权限列表
      const { data: res } = await this.$http.get('rights/tree')
      this.rightsList = res.data

      // 把已有的权限id存到checkedKeys
      this.getCheckedKeys(role, this.checkedKeys)
    },

    //把拥有的权限放checkedKeys中
    getCheckedKeys(role, arr) {
      // 没有children 则说明是三级菜单
      if (!role.children) {
        return arr.push(role.id)
      }
      // 不是三级菜单  就让children运行这个函数
      role.children.forEach((role) => {
        this.getCheckedKeys(role, arr)
      })
    },
    // 关闭分配权限对话框后  重置checkedKeys数组
    closeSetRight() {
      this.checkedKeys = []
    },

    // 分配权限
    async allotRights() {
      const arr = [
        ...this.$refs.rightsListRef.getCheckedKeys(),
        ...this.$refs.rightsListRef.getHalfCheckedKeys(),
      ]
      this.rids = arr.join(',')
      // 角色授权
      const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        { rids: this.rids }
      )

      if (res.meta.status !== 200) this.$message.error('404 NotFound')
      // 提交成功
      this.$message.success('更新成功')
      this.setRightDialogVisible = false
      // 更新数据
      this.getRolesList()
    },
  },
}
</script>

<style lang="less" scoped>
.el-table {
  margin-top: 15px;
}
.el-tag {
  margin: 7px;
}
.bd_top {
  border-top: 1px solid #ccc;
}
.bd_bottom {
  border-bottom: 1px solid #ccc;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>